package top.shiyiri.json;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;
import top.shiyiri.pojo.Person;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author Aunean
 * @date 2022/2/12 19:44
 */
public class JsonTest {

    //Java和json的互转
    @Test
    public void test1() {
        Person person = new Person(1, "张三");
        System.out.println(person);
        //创建Gson实例
        Gson gson = new Gson();

        //toJson()方法可以把Java对象转换成为json字符串
        String toJson = gson.toJson(person);
        System.out.println(toJson);

        //fromJson()把json字符串转换回Java对象类型
        //第一个参数是json字符串
        //第二个参数是转换回去的Java对象类型
        Person person1 = gson.fromJson(toJson, Person.class);
        System.out.println(person1);
    }

    //List和json的互转
    @Test
    public void test2() {
        ArrayList<Person> people = new ArrayList<>();
        people.add(new Person(1, "颤三"));
        people.add(new Person(2, "李四"));
        people.add(new Person(3, "盎维"));

        Gson gson = new Gson();

        String toJson = gson.toJson(people);
        System.out.println(toJson);

        ArrayList<Person> person = gson.fromJson(toJson, new PersonListType().getType());
        System.out.println(person);
    }

    //map和json的互转
    @Test
    public void test3() {
        HashMap<Integer, Person> map = new HashMap<>();
        map.put(1, new Person(1, "颤三"));
        map.put(2, new Person(2, "颤三"));
        map.put(3, new Person(3, "颤三"));

        Gson gson = new Gson();

        String toJson = gson.toJson(map);
        System.out.println(toJson);

        HashMap<Integer, Person> fromJson = gson.fromJson(toJson, new TypeToken<HashMap<Integer, Person>>(){}.getType());
//        HashMap<Integer, Person> fromJson = gson.fromJson(toJson, new PersonMapType().getType());
        System.out.println(fromJson);

    }
}
